﻿import "dotenv/config";
import express from "express";
import http from "http";
import { Server } from "socket.io";
import cors from "cors";
import helmet from "helmet";
import morgan from "morgan";

// 路由
import auth from "./routes/auth";
import map from "./routes/map";
import heatmap from "./routes/heatmap";
import routePlan from "./routes/route";
import simulate from "./routes/simulate";
import optimize from "./routes/optimize";
import assets from "./routes/assets";
import scene from "./routes/scene";
import alerts from "./routes/alerts";
import drug from "./routes/drug";
import ocr from "./routes/ocr";
import cloudrender from "./routes/cloudrender";
import admin from "./routes/admin";
import face from "./routes/face";
import email from "./routes/email";
import patientAuth from "./routes/patient-auth";
import wxappAuth from "./routes/wxapp-auth";
import adminWxapp from "./routes/admin-wxapp";
import location from "./routes/location";
import appointment from "./routes/appointment";
import ai from "./routes/ai";
import patientStats from "./routes/patient-stats";
import hospitalSite from "./routes/hospital-site";
import banner from "./routes/banner";
import { authenticateWxAppToken } from "./middleware/wxapp-auth";
import { authenticateToken } from "./middleware/auth";

const app = express();
app.use(cors({ origin: process.env.CORS_ORIGIN || "*" }));
app.use(helmet());
app.use(express.json({ limit: "2mb" }));
app.use(express.urlencoded({ extended: true, limit: "2mb" }));
app.use(morgan("dev"));

// 调试中间件
app.use((req, res, next) => {
  if (req.path.includes('/liveness')) {
    console.log(`[DEBUG] ${req.method} ${req.path}`);
    console.log(`[DEBUG] Content-Type: ${req.get('Content-Type')}`);
    console.log(`[DEBUG] Body:`, req.body);
  }
  next();
});

// v1 API路由
app.use("/v1/auth", auth);
app.use("/v1/map", map);
app.use("/v1/heatmap", heatmap);
app.use("/v1/route", routePlan);
app.use("/v1/simulate", simulate);
app.use("/v1/optimize", optimize);
app.use("/v1/assets", assets);
app.use("/v1/scene", scene);
app.use("/v1/ocr", ocr);
app.use("/v1/cloudrender", cloudrender);
app.use("/v1/admin", admin);
app.use("/v1/face", face);
app.use("/v1/email", email);
app.use("/v1/alerts", alerts);
app.use("/v1/drug", drug);
app.use("/v1/patient", patientAuth);
app.use("/v1/location", location);
app.use("/v1/appointment", appointment);
app.use("/v1/ai", ai);
app.use("/v1/patient-stats", patientStats);
app.use("/v1/hospital-site", hospitalSite);
app.use("/v1/banner", banner);

// wxapp API 路由
// 注意：只挂载一次基础前缀，路由细分在 wxapp-auth.ts 内部定义
app.use("/api/wxapp/auth", wxappAuth);

// 管理端的wxapp用户管理（需要后台管理员权限）
app.use("/api/admin", authenticateToken, adminWxapp);

// 健康检查接口
app.get("/health", (req, res) => {
  res.json({ 
    status: "ok", 
    timestamp: new Date().toISOString(),
    version: "1.0.0"
  });
});

const server = http.createServer(app);
const io = new Server(server, { cors: { origin: process.env.CORS_ORIGIN || "*" } });

// WebSocket 命名空间
io.of("/ws/simulate").on("connection", (s) => {
  s.emit("progress", { runId: "r_demo", progress: 10, eta: 120 });
});
io.of("/ws/alerts").on("connection", (s) => {
  s.emit("alert.new", { id: "a1", type: "crowd", level: "L1", startedAt: new Date().toISOString() });
});
io.of("/ws/viewer").on("connection", (s) => {
  s.on("control", (msg) => s.broadcast.emit("control", msg));
});

const port = Number(process.env.PORT || 8080);
server.listen(port, () => console.log(`[api] listening on :${port}`));
